package dk.iha;

import java.io.IOException;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.util.Log;

public class ConnectBTDeviceThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final UUID SSP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private Handler reportHandler = null;
    
    /**
     * returns the connected socket
     * @return
     */
    public BluetoothSocket getSocket(){
    	return mmSocket;
    }
     /**
     * 
     * @param device
     * @param reportHandler callback handler 
     */
    public ConnectBTDeviceThread(BluetoothDevice device, Handler reportHandler) {
        // Use a temporary object that is later assigned to mmSocket, because mmSocket is final
    	this.reportHandler = reportHandler;
        BluetoothSocket tmp = null;
 
        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
        	//use insecure connection to device
    		SharedData.getInstance().addDebugDataLog_t("ConnectBTDeviceThread device:"+(device == null ? "null":device.getAddress()));
    		if(device != null)
    			tmp = device.createInsecureRfcommSocketToServiceRecord(SSP_UUID);
            //tmp = device.createRfcommSocketToServiceRecord(SSP_UUID);
        } catch (IOException e) { 
			SharedData.getInstance().addDebugDataLog_t("createInsecureRfcommSocketToServiceRecord FAILED");
        	tmp = null;
        }
        
        mmSocket = tmp; 
    }
 
    
    public void run() {
        // Cancel discovery because it will slow down the connection
		int success=1;// 1 = success, -1=fail

		BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
		
		try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
    		mmSocket.connect();
	        //connection succeeded
        } catch (IOException connectException) { 
        	success=-1;
            // Unable to connect; close the socket  
            try {
	        	if(mmSocket != null)
	        		mmSocket.close();
            } catch (IOException closeException) {
            	//error
            }
		}
        //report back to caller
		reportHandler.sendEmptyMessage(success);
    }
 
    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
        	if(mmSocket != null)
        		mmSocket.close();
        } catch (IOException e) { }
    }
}